import { getSmNavigateSettingList } from '@/api/decoration'
import { defineStore } from 'pinia'

interface TabbarItem {
  navigateName: string
  selectImg: string
  unselectImg: string
  linkUrl: string
}

const switchTabPages = ['/pages/index', '/pages/tabbar/mine']
const useTabbarStore = defineStore('tabbar', {
  state: () => ({
    tabbarList: [
      {
        navigateName: '首页',
        selectImg: 'https://healthcare2024.oss-cn-beijing.aliyuncs.com/1539bba6-33bb-4e72-abdd-2fb402b919af.png',
        unselectImg: 'https://healthcare2024.oss-cn-beijing.aliyuncs.com/10d7782f-029c-4007-b90f-c2c117726ba1.png',
        linkUrl: '/pages/index'
      },
      {
        navigateName: '我的',
        selectImg: 'https://healthcare2024.oss-cn-beijing.aliyuncs.com/12465e3c-9acb-44e3-ae35-97c6563eec5e.png',
        unselectImg: 'https://healthcare2024.oss-cn-beijing.aliyuncs.com/0de9c4ed-66ca-4c35-a15d-c11dfb211b62.png',
        linkUrl: '/pages/tabbar/mine'
      }
    ] as TabbarItem[], // 初始为空，动态生成
    activeTab: 0, // 当前激活的 tab 索引
    activeTabName: '', // 当前激活的 tab 名称
    activeColor: '#000',
    unactiveColor: '#333'
  }),
  actions: {
    /**
     * 动态设置 tabbarList
     * @param list TabbarItem[]
     */
    setTabbarList(list: TabbarItem[]) {
      this.tabbarList = list
    },

    /**
     * 获取 TabBar 列表
     */
    async fetchTabbarList() {
      // 模拟从后端 API 获取 tabbar 列表
      const response = await getSmNavigateSettingList()
      const tabbarList = response.data.result.map((i: any, index: number) => {
        return {
          navigateName: i.navigateName,
          selectImg: i.selectImg,
          unselectImg: i.unselectImg,
          linkUrl:
            index === 0 ? '/pages/index' : index === response.data.result.length - 1 ? '/pages/tabbar/mine' : i.linkUrl
        }
      })
      this.setTabbarList(tabbarList)
    },

    /**
     * 切换 TabBar
     * @param index 索引
     */
    tabSwitch(index: number) {
      if (index === this.activeTab) {
        return
      }
      this.activeTab = index
      const target = this.tabbarList[index]
      this.activeTabName = target.navigateName
      if (target) {
        // 根据路径自定义跳转方式
        if (switchTabPages.includes(target.linkUrl)) {
          // 普通页面跳转
          uni.switchTab({ url: target.linkUrl })
        } else {
          // 自定义跳转逻辑
          uni.reLaunch({ url: target.linkUrl })
        }
      }
    },
    /**
     * 手动设置 activeTab, 防止不是点击底部导航栏跳转的tabbar页面
     * @param index 索引
     */
    setActiveTab(index: number) {
      this.activeTab = index
    }
  }
})

export default useTabbarStore
